package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者
 */
public class ProducerQuickStart {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1. kafka链接配置信息
        Properties prop = new Properties();
        // 1.1 kafka链接地址
        prop.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.174.133:9092");
        // 1.2 key和value的序列化
        prop.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        prop.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        // 1.3 设置消息确认
        prop.put(ProducerConfig.ACKS_CONFIG, "all");
        // 1.4 设置消息重传
        prop.put(ProducerConfig.RETRIES_CONFIG, 10);
        // 1.5 设置消息压缩
        prop.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");

        // 2. 创建kafka生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<>(prop);
        // 3. 发送信息
        // 参数列表: topic, key, value
        // ProducerRecord<String, String> record = new ProducerRecord<>("topic-first", "key1", "Hello Kafka!");
        for (int i = 0; i < 5; i++) {
            ProducerRecord<String, String> kvProducerRecord = new ProducerRecord<>("itcast-topic-input", "hello kafka");
            producer.send(kvProducerRecord);
        }

        // 同步发送
        // RecordMetadata metadata = producer.send(record).get();
        // System.out.println(metadata.offset());

        // 异步发送
        // producer.send(record, new Callback(){
        //     @Override
        //     public void onCompletion(RecordMetadata recordMetadata, Exception e) {
        //         if(e != null) {
        //             System.out.println("记录异常信息到日志表中");
        //         }
        //         System.out.println(recordMetadata.offset());
        //     }
        // });

        // 4. 关闭消息通道
        // 必须关闭, 否则消息发送不成功
        producer.close();
    }
}
